import axios from 'axios'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 30000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 添加token到请求头
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 主机管理API
export const hostAPI = {
  getList: (params) => request.get('/hosts/', { params }),
  getDetail: (id) => request.get(`/hosts/${id}/`),
  create: (data) => request.post('/hosts/', data),
  update: (id, data) => request.put(`/hosts/${id}/`, data),
  delete: (id) => request.delete(`/hosts/${id}/`),
  testConnection: (id) => request.post(`/hosts/${id}/test_connection/`)
}

// 主机组管理API
export const hostGroupAPI = {
  getList: (params) => request.get('/host-groups/', { params }),
  getDetail: (id) => request.get(`/host-groups/${id}/`),
  create: (data) => request.post('/host-groups/', data),
  update: (id, data) => request.put(`/host-groups/${id}/`, data),
  delete: (id) => request.delete(`/host-groups/${id}/`)
}

// 项目管理API
export const projectAPI = {
  getList: (params) => request.get('/projects/', { params }),
  getDetail: (id) => request.get(`/projects/${id}/`),
  create: (data) => request.post('/projects/', data),
  update: (id, data) => request.put(`/projects/${id}/`, data),
  delete: (id) => request.delete(`/projects/${id}/`)
}

// 环境管理API
export const environmentAPI = {
  getList: (params) => request.get('/environments/', { params }),
  getDetail: (id) => request.get(`/environments/${id}/`),
  create: (data) => request.post('/environments/', data),
  update: (id, data) => request.put(`/environments/${id}/`, data),
  delete: (id) => request.delete(`/environments/${id}/`)
}

// 用户管理API
export const userAPI = {
  getList: (params) => request.get('/users/', { params }),
  getDetail: (id) => request.get(`/users/${id}/`),
  create: (data) => request.post('/users/', data),
  update: (id, data) => request.put(`/users/${id}/`, data),
  delete: (id) => request.delete(`/users/${id}/`)
}

// 用户组管理API
export const userGroupAPI = {
  getList: (params) => request.get('/user-groups/', { params }),
  getDetail: (id) => request.get(`/user-groups/${id}/`),
  create: (data) => request.post('/user-groups/', data),
  update: (id, data) => request.put(`/user-groups/${id}/`, data),
  delete: (id) => request.delete(`/user-groups/${id}/`)
}

// 认证API
export const authAPI = {
  register: (data) => request.post('/auth/register/', data),
  login: (data) => request.post('/auth/login/', data),
  logout: (data) => request.post('/auth/logout/', data),
  getUserInfo: () => request.get('/auth/user/')
}

export default request
